package com.iisigroup.http.test;


import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.iisigroup.http.test.RlAccount.Account;
/**
 * Hello world!
 * 參考https://hc.apache.org/httpcomponents-client-4.3.x/quickstart.html
 * 而做出來的測試程式碼
 */
public class App2 {

	public static void main(String[] args) throws Exception {
	    new App2().testMethod();
//		new App2().multiProcess();
	}
	
	public void testMethod() throws ClientProtocolException, IOException{
		
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// The underlying HTTP connection is still held by the response object
		// to allow the response content to be streamed directly from the network socket.
		// In order to ensure correct deallocation of system resources
		// the user MUST call CloseableHttpResponse#close() from a finally clause.
		// Please note that if response content is not fully consumed the underlying
		// connection cannot be safely re-used and will be shut down and discarded
		// by the connection manager. 
		
		//HttpPost httpPost = new HttpPost("http://www.masmas.com.tw/%E6%90%9C%E5%B0%8B/action-collect_search.htm");
		HttpPost httpPost = new HttpPost("http://www.masmas.com.tw/collect/ajax/ajax_love-p.php");
		//http://www.masmas.com.tw/collect/ajax/ajax_love-p.php
		List <NameValuePair> nvps = new ArrayList <NameValuePair>();
		Account account = 	RlAccount.getRandomAccount();
		//http://www.masmas.com.tw/%E4%B8%91%E5%85%92%E2%80%A7%E7%86%8A%E5%85%92%E5%92%8C%E9%B3%A5%E5%85%92/action-collect_detail-cid-8-did-2240.htm
//		nvps.add(new BasicNameValuePair("search_str", "丑兒‧熊兒和鳥兒"));
//		nvps.add(new BasicNameValuePair("x", "21"));
//		nvps.add(new BasicNameValuePair("y", "17"));
		nvps.add(new BasicNameValuePair("ID", "2240"));
		//ID=2240
		httpPost.setEntity(new UrlEncodedFormEntity(nvps,"UTF8"));
		CloseableHttpResponse response2 = httpclient.execute(httpPost);

		try {
		    System.out.println(response2.getStatusLine());
		    HttpEntity entity2 = response2.getEntity();
		    InputStream ins = entity2.getContent();
   	             final List<String> lines = IOUtils.readLines(ins);
   	            for (String line : lines) {
   		         System.out.println(line);
   	              }
		    
		    // do something useful with the response body
		    // and ensure it is fully consumed
		    EntityUtils.consume(entity2);
		} finally {
		    response2.close();
		}
		 
		
		//如果要測試戶籍員的反應...則要把httpclient.close();註解掉,這樣才會使得stuck thread 不會消失
//		httpclient.close();
	}
	public void multiProcess(){
		List<Future<List<String>>> data =null;
		final List<HttpTask> tasks = new ArrayList<HttpTask>();
		for(int j=0 ;j<1000;++j){
			tasks.add(new HttpTask());
		}
		ExecutorService service = Executors.newFixedThreadPool(250);
        
        try {
        	 data = service.invokeAll(tasks, 10000, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
            service.shutdown();
        }
        if(data != null && data.size() > 0){
        	for(Future<List<String>> futureUnit :data ){
        		try {
					futureUnit.get();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}	
        	}
        }
	}
	public class HttpTask implements Callable<List<String>> {

		@Override
		public List<String> call() throws Exception {
			testMethod();
			return null;
		}}
}
